package com.ruoyi.gd.ywd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.gd.wgd.domain.vo.ZWgdVo;
import com.ruoyi.gd.wgd.mapper.ZWgdMapper;
import com.ruoyi.gd.xcaplog.domain.ZXcapLog;
import com.ruoyi.gd.xcaplog.mapper.ZXcapLogMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.stereotype.Service;
import com.ruoyi.gd.ywd.domain.bo.ZYwdBo;
import com.ruoyi.gd.ywd.domain.vo.ZYwdVo;
import com.ruoyi.gd.ywd.domain.ZYwd;
import com.ruoyi.gd.ywd.mapper.ZYwdMapper;
import com.ruoyi.gd.ywd.service.IZYwdService;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务单Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-17
 */
@RequiredArgsConstructor
@Service
public class ZYwdServiceImpl implements IZYwdService {

    private final ZYwdMapper baseMapper;
    @Resource
    private ISysDictTypeService dictTypeService;

    @Resource
    private ZXcapLogMapper zcapLogMapper;

    @Resource
    private ZWgdMapper zwgdMapper;

    @Resource
    private ZWgdMapper wgdMapper;

    @Resource
    private ISysConfigService configService;

    /**
     * 查询业务单
     */
    @Override
    public ZYwdVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询业务单列表
     */
    @Override
    public TableDataInfo<ZYwdVo> queryPageList(ZYwdBo bo, PageQuery pageQuery, String type) {
//        LambdaQueryWrapper<ZYwd> lqw = buildQueryWrapper(bo, type);
//        Page<ZYwdVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
//        result.getRecords().forEach(item -> {
//            String zbbh = item.getZbbh();
//            if (StringUtils.isNotEmpty(zbbh)) {
//                List<ZWgdVo> zWgdVoList = zwgdMapper.selectByZbbhId(zbbh);
//                // 判断当前的完工单是否为空，并且附件不为空
//                if(zWgdVoList.size() > 0 && StringUtils.isNotEmpty(zWgdVoList.get(0).getFj())) {
//                    item.setWgdsfws("true");
//                    item.setWgbh(zWgdVoList.get(0).getWgbh());
//                }else {
//                    item.setWgdsfws("false");
//                }
//            }
//        });
        StringUtils.trimEntityFields(bo);
        bo.setType(type);
        LoginUser loginUser = LoginHelper.getLoginUser();
        // 设置用户
        bo.setIsAdmin(loginUser.getUsername());
        // 1.通过字典数据，哪些用户可以获取所有数据
        List<String> khGetAllData = dictTypeService.selectDictDataByType("kh_getAllData").stream().map(SysDictData::getDictValue).collect(Collectors.toList());
        // 判断字典数据中的id在集合中是否存在
        boolean b = khGetAllData.stream().anyMatch(val -> val.equals(loginUser.getUserId().toString()));
        // 如果当前用户不存在则查询所有
        if (!b) {
            bo.setCreateId(loginUser.getUserId()+"");
        }
        Page<ZYwdVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        // 开始分页
        List<ZYwdVo> result = baseMapper.queryList(page, bo);
        page.setRecords(result);
        return TableDataInfo.build(page);
    }

    /**
     * 查询业务单列表
     */
    @Override
    public List<ZYwdVo> queryList(ZYwdBo bo, String type) {
        LambdaQueryWrapper<ZYwd> lqw = buildQueryWrapper(bo, type);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZYwd> buildQueryWrapper(ZYwdBo bo, String type) {
        LambdaQueryWrapper<ZYwd> lqw = Wrappers.lambdaQuery();
        try {
            // 处理空格数据
            bo.setZbbh(StringUtils.trimField(bo, "zbbh"));
            bo.setKh(StringUtils.trimField(bo, "kh"));

            LoginUser loginUser = LoginHelper.getLoginUser();
            // 1.通过字典数据，哪些用户可以获取所有数据
            List<String> khGetAllData = dictTypeService.selectDictDataByType("kh_getAllData").stream().map(SysDictData::getDictValue).collect(Collectors.toList());
            // 判断字典数据中的id在集合中是否存在
            boolean b = khGetAllData.stream().anyMatch(val -> val.equals(loginUser.getUserId().toString()));
            // 如果当前用户不存在则查询所有
            if (!b) {
                lqw.eq(true, ZYwd::getCreateId, loginUser.getUserId());
            }
            lqw.like(StringUtils.isNotBlank(bo.getZbbh()), ZYwd::getZbbh, bo.getZbbh());
            lqw.eq(StringUtils.isNotBlank(bo.getFj()), ZYwd::getFj, bo.getFj());
            lqw.eq(StringUtils.isNotBlank(bo.getFjpdf()), ZYwd::getFjpdf, bo.getFjpdf());
            if (bo.getXcsj() != null) {
                lqw.ge(ZYwd::getXcsj, bo.getStartXcsj()) // 大于等于今天的开始时间
                    .lt(ZYwd::getXcsj, bo.getEndXcsj()); // 小于今天的结束时间
            }
            // 是否回款
            if (StringUtils.isNotEmpty(bo.getSfhk())) {
                List<String> strings = Arrays.asList(bo.getSfhk().split(","));
                lqw.in(ZYwd::getSfhk, strings);
            }

            // 查询送检方式是已送检或者待安排下场的数据
            if(type.equals("xcap")) {
                lqw.and(wrapper -> wrapper.eq(ZYwd::getJcfs, "1").like(ZYwd::getSfyxc, bo.getSfyxc()));
                lqw.or(wrapper -> wrapper.eq(ZYwd::getJcfs, "2").like(ZYwd::getSjzt, bo.getSjzt()));
            }else {
                lqw.eq(StringUtils.isNotBlank(bo.getSjzt()), ZYwd::getSjzt, bo.getSjzt());
                if (StringUtils.isNotEmpty(bo.getSfyxc())) {  // 是否已下场
                    List<String> strings = Arrays.asList(bo.getSfyxc().split(","));
                    lqw.in(ZYwd::getSfyxc, strings);
                }
            }

            lqw.eq(bo.getHksj() != null, ZYwd::getHksj, bo.getHksj());
            lqw.eq(StringUtils.isNotBlank(bo.getBz()), ZYwd::getBz, bo.getBz());
            lqw.like(!StringUtils.isEmpty(bo.getKh()), ZYwd::getKh, "%" + bo.getKh() + "%");
            lqw.like(!StringUtils.isEmpty(bo.getDz()), ZYwd::getDz, "%" + bo.getDz() + "%");
            lqw.like(!StringUtils.isEmpty(bo.getCreateBy()), ZYwd::getCreateBy, "%" + bo.getCreateBy() + "%");
            lqw.eq(StringUtils.isNotBlank(bo.getJcfs()), ZYwd::getJcfs, bo.getJcfs());

            if (bo.getCreateTime() != null || (bo.getStartCreateTime() != null && bo.getEndCreateTime() != null)) {
                lqw.ge(ZYwd::getCreateTime, bo.getStartCreateTime()) // 大于等于今天的开始时间
                    .lt(ZYwd::getCreateTime, bo.getEndCreateTime()); // 小于今天的结束时间
            }
            if (bo.getXcpx() != null && bo.getXcpx()) {
                lqw.orderByAsc(ZYwd::getSfyxc);
            }

            if(!"admin".equals(loginUser.getUsername())) {
                List<String> strings = Arrays.asList("0");
                lqw.in(ZYwd::getDelFlag, strings);
            }

            // 添加时间条件
            if (bo.getParams()!=null && bo.getParams().size() > 0) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 设置下场时间
                Object start = bo.getParams().get("startTime");
                Object end = bo.getParams().get("endTime");
                if (null != start && null != end) {
                    Date startTime = format.parse((String) start);
                    Date endTime = format.parse((String) end);
                    if (startTime != null && endTime != null) {
                        lqw.ge(ZYwd::getXcsj, startTime);
                        lqw.le(ZYwd::getXcsj, endTime);
                    }
                }
                // 设置回款时间
                SimpleDateFormat formatNYR = new SimpleDateFormat("yyyy-MM-dd");
                Object startHkTime = bo.getParams().get("startHkTime");
                Object endHkTime = bo.getParams().get("endHkTime");
                if (null != startHkTime && null != endHkTime) {
                    Date startTime = formatNYR.parse((String) startHkTime);
                    Date endTime = formatNYR.parse((String) endHkTime);
                    if (startTime != null && endTime != null) {
                        lqw.ge(ZYwd::getHksj, startTime);
                        lqw.le(ZYwd::getHksj, endTime);
                    }
                }
                // 设置回款金额
                Object minJe = bo.getParams().get("minJe");
                Object maxJe = bo.getParams().get("maxJe");
                if (null != minJe && null != maxJe) {
                    double minJeQ = Double.parseDouble(minJe.toString());
                    double maxJeQ = Double.parseDouble(maxJe.toString());
                    if (minJeQ > 0 && maxJeQ > 0 ) {
                        lqw.ge(ZYwd::getHkje, minJeQ);
                        lqw.le(ZYwd::getHkje, maxJeQ);
                    }
                }
                // 设置判断当前的完善状态
                Object wszt = bo.getParams().get("wszt");
                if (null != wszt && StringUtils.isNotEmpty(wszt.toString())) {
                    // 判断当前的完善状态
                    String[] split = wszt.toString().split(",");
                    if (split.length == 1) {
                        for (String s : split) {
                            // 判断当前的添加是否有完善
                            if ("ws".equals(s)) {
                                lqw.isNotNull(ZYwd::getFj);
                            }
                            if ("dws".equals(s)) {
                                lqw.isNull(ZYwd::getFj);
                            }
                        }
                    }
                }
            }

            lqw.orderByDesc(ZYwd::getCreateTime);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return lqw;
    }

    /**
     * 新增业务单
     */
    @Override
    public Boolean insertByBo(ZYwdBo bo) {
        ZYwd add = BeanUtil.toBean(bo, ZYwd.class);
        LoginUser loginUser = LoginHelper.getLoginUser();
        add.setCreateId(loginUser.getUserId()+"");
        if (!validEntityBeforeSave(add)) {
            throw new RuntimeException(add.getZbbh() + " 编号已经存在");
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            // 判断是否需要记录日志
            if(StringUtils.isNotEmpty(bo.getIsLog()) && bo.getIsLog().equals("true")) {
                // 记录日志
                ZXcapLog zXcapLog = new ZXcapLog();
                zXcapLog.setXcid(add.getId());
                zXcapLog.setXcfzrid(add.getXcfzrid());
                zXcapLog.setXcfzrname(add.getXcfzrname());
                zXcapLog.setXclx(add.getXclx());
                zXcapLog.setXcbz(add.getXcbz());
                zXcapLog.setXcsj(add.getXcsj());
                zXcapLog.setXcrid(add.getXcryid());
                zXcapLog.setXcrname(add.getXcryname());
                zXcapLog.setCreatetime(new Date());
                zcapLogMapper.insert(zXcapLog);
            }
        }
        return flag;
    }

    /**
     * 修改业务单
     */
    @Override
    public Boolean updateByBo(ZYwdBo bo) {
        ZYwd update = BeanUtil.toBean(bo, ZYwd.class);
        boolean b = baseMapper.updateById(update) > 0;
        // 判断是否需要记录日志
        if(StringUtils.isNotEmpty(bo.getIsLog()) && bo.getIsLog().equals("true")) {
            // 记录日志
            ZXcapLog zXcapLog = new ZXcapLog();
            zXcapLog.setXcid(update.getId());
            zXcapLog.setXcfzrid(update.getXcfzrid());
            zXcapLog.setXcfzrname(update.getXcfzrname());
            zXcapLog.setXclx(update.getXclx());
            zXcapLog.setXcbz(update.getXcbz());
            zXcapLog.setXcsj(update.getXcsj());
            zXcapLog.setXcrid(update.getXcryid());
            zXcapLog.setXcrname(update.getXcryname());
            zXcapLog.setCreatetime(new Date());
            zcapLogMapper.insert(zXcapLog);
        }
        return b;
    }

    /**
     * 保存前的数据校验
     */
    private boolean validEntityBeforeSave(ZYwd entity){
        //TODO 做一些数据校验,如唯一约束
        QueryWrapper<ZYwd> wrapper = new QueryWrapper<>();
        wrapper.eq("zbbh", entity.getZbbh());
        wrapper.eq("del_flag", "0");
        Long aLong = baseMapper.selectCount(wrapper);
        return aLong == 0;
    }

    /**
     * 批量删除业务单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.batchDeleteIds(ids) > 0;
    }

    @Override
    public List<ZYwdVo> queryListByIds(String ids) {
        String[] split = ids.split(",");
        List<ZYwdVo> list = baseMapper.selectByIds(split);
        return list;
    }

    @Override
    public Boolean authData(String[] ids) {
        return baseMapper.updateBatchByIds(ids) > 0;
    }

    // 通过编号更新下场状态
    @Override
    public void updateByZbbh(String zbbh) {
        ZYwd zYwd = new ZYwd();
        zYwd.setZbbh(zbbh);
        zYwd.setSfyxc("3");
        baseMapper.updateByZbbh(zYwd);
    }

    @Override
    public List<ZYwdVo> calendarList(ZYwdBo bo) {
        List<ZYwdVo> zYwdVos = baseMapper.calendarList(bo.getSfyxc());
        return zYwdVos;
    }

    @Override
    public List<ZYwdVo> querySyList(LambdaQueryWrapper<ZYwd> lqw) {
        List<ZYwdVo> zYwdVos = baseMapper.selectVoList(lqw);
        return zYwdVos;
    }

    @Override
    public List<ZYwdVo> handleSyTz() {
        List<ZYwdVo> result = new ArrayList<>();
        // 1.获取当前天数的前三天日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        int dayNum = Integer.parseInt(configService.selectConfigByKey("sy_dzwgdcx"));
        LocalDateTime currentDate = LocalDateTime.now();
        LocalDateTime twoDaysAgo = currentDate.minusDays(dayNum);
        String wgjs = twoDaysAgo.format(formatter);  // 完工结束
        // 获取当前的时间的下场数据
        LambdaQueryWrapper<ZYwd> lqw = Wrappers.lambdaQuery();
        lqw.le(ZYwd::getXcsj, wgjs + " 23:59:59");  // 设置下场时间条件
        List<ZYwdVo> zYwdVos = baseMapper.selectVoList(lqw);
        for (ZYwdVo zYwdVo : zYwdVos) {
            String zbbh = zYwdVo.getZbbh();
            if (StringUtils.isNotEmpty(zbbh)) {
                List<ZWgdVo> zWgdVoList = wgdMapper.selectByZbbhId(zbbh);
                // 判断当前的完工单是否为空，并且附件不为空
                if(zWgdVoList.size() > 0 && StringUtils.isEmpty(zWgdVoList.get(0).getFj())) {
                    zYwdVo.setWgdsfws("false");
                    zYwdVo.setWgbh(zWgdVoList.get(0).getWgbh());
                    result.add(zYwdVo);
                }else if (zWgdVoList.size() == 0) {
                    zYwdVo.setWgdsfws("false");
                    result.add(zYwdVo);
                }
            }
        }
        return result;
    }

    @Override
    public List<ZYwdVo> selectByIds(String[] ids) {
        return baseMapper.selectByIds(ids);
    }

    @Override
    public List<ZYwdVo> selectByIdsWgd(String[] ids) {
        return baseMapper.selectByIdsWgd(ids);
    }

}
